/*
 * @Author: EyeSklear 1814580085@qq.com
 * @Date: 2024-03-04 20:27:13
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-04-26 16:48:16
 * @FilePath: \Scene_Back\src\path-list\path-list.service.ts
 * @Description:
 *
 * Copyright (c) 2024 by EyeSklear , All Rights Reserved.
 */
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreatePathListDto } from './dto/create-path-list.dto';
import { UpdatePathListDto } from './dto/update-path-list.dto';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { PathList } from './entities/path-list.entity';

@Injectable()
export class PathListService {
  constructor(
    @InjectRepository(PathList)
    private readonly pathListRepository: Repository<PathList>,
  ) {}

  async create(createPathListDto: CreatePathListDto) {
    const insertPathItem = await this.pathListRepository.insert(
      this.pathListRepository.create(createPathListDto),
    );
    return insertPathItem.raw[0].id;
  }

  async findAll(): Promise<PathList[]> {
    return this.pathListRepository.find();
  }

  async findOne(id: string): Promise<PathList> {
    return this.pathListRepository.findOne({ where: { id: id } });
  }

  async getPathByPathIdsAndType(
    type: string,
    pathIds: string[],
  ): Promise<PathList[]> {
    return this.pathListRepository
      .createQueryBuilder('path_list')
      .where('path_list.type = :type', { type })
      .andWhere('path_list.id IN (:...pathIds)', { pathIds })
      .getMany();
  }

  async getPathByPathIds(pathIds: string[]): Promise<PathList[]> {
    return this.pathListRepository
      .createQueryBuilder('path_list')
      .where('path_list.id IN (:...pathIds)', { pathIds })
      .orderBy('path_list.create_time', 'ASC')
      .getMany();
  }

  async update(id: string, updatePathListDto: UpdatePathListDto) {
    const oldItem = await this.pathListRepository.findOne({
      where: { id },
    });
    if (!oldItem) {
      throw new NotFoundException('该修改对象不存在');
    }
    const updatedPathList = this.pathListRepository.merge(
      oldItem,
      updatePathListDto,
    );

    await this.pathListRepository.save(updatedPathList);

    // 返回更新后的实体或其他有用的信息
    return updatedPathList;
  }

  async remove(id: string) {
    //删除pathlist中的记录
    const result = await this.pathListRepository.delete({ id: id });
    if (result.affected && result.affected > 0) {
      //删除path_item_relational中的记录

      //删除对应的item记录

      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }
}
